<?php

namespace app\admin\controller\facrm;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\Queue;


/**
 * 待办事项
 */
class Backlog extends Backend
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'customer_id,name,mobile,telephone';
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);

    }
    /**
     * 列表
     */
    public function index($types="contract")
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $scene_list = ['contract'=>"合同审批",'receivables'=>'回款审批','invoice'=>'发票审批'];
        if ($this->request->isAjax()) {
            $filter_w = [];
            if(!$model_str=\app\admin\model\facrm\Flow::getModelStr($types)){
				 $this->error(__("审核类型有误"));
			}
           
            $this->model = model($model_str);
            //$filter_w[]=['exp','FIND_IN_SET('. $this->auth->id.',flow_admin_id)'];
           // $filter_w[]=['exp','FIND_IN_SET(2,flow_admin_id)'];
            $filter_w['check_status'] =['in',[0,1]];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->where('','exp','FIND_IN_SET('. $this->auth->id.',flow_admin_id)')
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $this->model
                ->where($where)
                ->where($filter_w)
                ->where('','exp','FIND_IN_SET('. $this->auth->id.',flow_admin_id)');


            switch ($types){
                case 'receivables':
                    $this->model->with([
                        'createUser' => function ($user) {
                            $user->field('id,username,nickname');
                        },
						'orderAdmin'=> function ($user) {
                            $user->field('id,username,nickname');
                        },
                        'customer' => function ($customer) {
                            $customer->field('id,name');
                        },
                        'contract' => function ($customer) {
                            $customer->field('id,name,number,money');
                        },
                    ]);
                    break;
                case "contract":
                    $this->model->with([
                        'createUser' => function ($user) {
                            $user->field('id,username,nickname');
                        },
                        'orderAdmin' => function ($user) {
                            $user->field('id,username,nickname');
                        },
                        'customer' => function ($customer) {
                            $customer->field('id,name');
                        },
                    ]);
                    break;
				case "invoice":
                    $this->model->with([
                        'createUser' => function ($user) {
                            $user->field('id,username,nickname');
                        },
                        'contract' => function ($user) {
                            $user->field('id,number,name');
                        },
                        'customer' => function ($customer) {
                            $customer->field('id,name');
                        },
                    ]);
                    break;

            }


            $list = $this->model->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {
            $this->view->assign("scene_list", $scene_list);
        }


        //当天开始时间
        $start_time=strtotime(date("Y-m-d",time()));
        //当天结束之间
        $end_time=$start_time+60*60*24;
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
        $customerModel = model('\app\admin\model\facrm\Customer');
        $cluesModel = model('\app\admin\model\facrm\Clues');
        //需要联系客户
        $communicate=$customerModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();
        //需要联系的线索
        $clues_num=$cluesModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();
        //将要过期的用户
        $lose_num=count($customerModel->getLose($this->childrenAdminIds));

        $businessModel = model('\app\admin\model\facrm\Business');
        $business=$businessModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();
        //是否有合同权限
        $contract_return=$contract_expire=0;
        if($this->auth->check('facrm/contract/index')){
            $contractModel = model('\app\admin\model\facrm\Contract');
            $filter_w['check_status']=2;
            //快过期和过期合同
            $contract_expire=$contractModel->where('end_time','between',[1,$end_time+(30*86400)])->where('expire_handle',0)->where($filter_w)->count();
            //待回款合同
            $contract_return=$contractModel->where("money","exp",">return_money")->where($filter_w)->count();
        }

        $this->view->assign([
            'communicate'=>$communicate,
            'lose_num'=>$lose_num,
            'business'=>$business,
            'contract_expire'=>$contract_expire,
            'contract_return'=>$contract_return,
            'clues_num'=>$clues_num,
        ]);
        return $this->view->fetch();
    }

    /**
     * 审核
     * @param null $ids
     */
    public function verify($ids = NULL,$types="contract")
    {
        if(!$model_str=\app\admin\model\facrm\Flow::getModelStr($types)){
            $this->error(__("审核类型有误"));
        }

        $this->model = model($model_str);
        $Log=model('\app\admin\model\facrm\flow\Log');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->check_status == [0,1]) {
            $this->error(__('不是待审核'));
        }

        if (!in_array($this->auth->id,explode(',',$row->flow_admin_id) )){
            $this->error(__('您没有权限审核'));
        }

        $flow=model('\app\admin\model\facrm\Flow');
        $flow_r=$flow->where('types',$types)->where("status",1)
            ->where('id',$row->flow_id)->find();

        if (!$flow_r){
            $row->check_status=3;
            $row->flow_id=0;
            $row->flow_admin_id=$row->check_admin_id="";//已审批的人清空
            $row->save();
            $this->error(__('审核流程已经不存在,已经直接驳回'));
        }



        if ($this->request->isPost()) {
            $flow_r->step=$flow_r->step()->where('id','>',$row->step_id)->select();
            $type = $this->request->post("type");
            $next_admin_id = $this->request->post("next_admin_id");
            $log_data=array();
            $log_data['flow_id']=$row->flow_id;
            $log_data['types']=$types;
            $log_data['types_id']=$row->id;
            $log_data['admin_id']=$this->auth->id;
            $log_data['nickname']=$this->auth->nickname;
            $log_data['remark']=$this->request->post("remark",'');
            $log_data['is_end']=0;
            $log_data['status']=0;//未通过
            Db::startTrans();
            try {
                //驳回
                if ($type=='reject'){
                    $row->check_status=3;
                    $row->check_admin_id="";//已审批的人清空
                }else{
                    //通过
                    //判断是否还有下一级审批人
                    if ($flow_r->config==1&&$flow_r->step){
                        $flow_admin_id=$flow_r->step[0]['admin_ids'];
                        if ($flow_r->step[0]['type']==1){
                            //上级领导审批
                            $Auth=new  \addons\facrm\library\Auth();
                            $parentIds= $Auth->getParentAdminIds($this->auth->id);
                            $flow_admin_id=$parentIds?join(',',$parentIds):$this->auth->id;//如果没有父类就是最高级的，同时也要审核一下
                        }else if ($flow_r->step[0]['type']==3){
                            //指定部门
                            $auth=new  \addons\facrm\library\Auth();
                            $groupIds=$auth->getGroupsAdminIds($flow_r->step[0]['admin_ids']);
                            $flow_admin_id=$groupIds?join(',',$groupIds):$this->auth->id;//如部门人自己也要审核一下

                        }
                        $row->check_status=1;
                        $row->flow_admin_id=$flow_admin_id;
                        $row->step_id=$flow_r->step[0]['id'];
                    }elseif ($flow_r->config==0&&$next_admin_id){
                        $row->check_status=1;
                        $row->flow_admin_id=$next_admin_id;
                    }else{
                        $row->flow_admin_id="";
                        $row->check_status=2;
                        $log_data['is_end']=1;
                    }
                    $row->check_admin_id.=$row->check_admin_id?','.$this->auth->id:$this->auth->id;
                    $log_data['status']=1;//通过
                }
                $row->save();
                //记录审核日志
                $Log->save($log_data);
                hook("facrm_flow_verify", array_merge($log_data, [
                    'id' => $Log->id,
                    'flow'=>$flow_r,
                ]));

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


            $this->success();
        }

        //获取审核日志
        $log_list=$Log->where('flow_id',$row->flow_id)->where('types_id',$row->id)->select();
        $this->view->assign("row", $row);
        $this->view->assign("flow", $flow_r);
        $this->view->assign("log_list", $log_list);
        switch ($types){
            case "contract":
                $this->view->assign("product_list", $row->product);
                break;
            case "receivables":
                $config = get_addon_config('facrm');
                $this->view->assign("account_list", $config['account']);
                break;
        }
        return $this->view->fetch($types);

    }

}
